package com.minelx.woods.server.controller;

import com.minelx.landisk.filesystem.core.Directory;
import com.minelx.landisk.filesystem.core.File;
import com.minelx.util.IOUtil;
import com.minelx.woods.server.entity.Tasks;
import com.minelx.woods.server.perspective.Authenticated;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static com.minelx.landisk.filesystem.core.init.OpenPolicy.useExisting;
import static com.minelx.landisk.filesystem.core.init.OpenPolicy.whatever;
import static org.springframework.http.ResponseEntity.ok;

@RestController
public class TaskController {
	private final Tasks tasks;

	private final Directory taskFilesDirectory;

	private final Map<UUID, String> downloadingRequest;

	public TaskController(Tasks tasks, Directory taskFilesDirectory) {
		this.tasks = tasks;
		this.taskFilesDirectory = taskFilesDirectory;
		downloadingRequest = new HashMap<>();
	}

	@Authenticated
	@GetMapping("task/{taskId}")
	ResponseEntity<?> id(@PathVariable String taskId) {
		return ok(tasks.id(taskId).values());
	}

	@Authenticated
	@PostMapping("task/downloadRequest/{taskId}")
	ResponseEntity<?> requestDownload(@PathVariable String taskId) {
		File destination = taskFilesDirectory.child().file(taskId, whatever());
		if (!destination.path().exists()) {
			return ResponseEntity.noContent().build();
		}
		// save request of taskId
		UUID requestId = UUID.randomUUID();
		downloadingRequest.put(requestId, taskId);
		return ok(Map.of("requestId", requestId.toString()));
	}

	@Authenticated
	@GetMapping("task/downloadRequest/{requestId}")
	void doDownload(HttpServletResponse response, @PathVariable String requestId) throws IOException {
		String fileName = downloadingRequest.remove(UUID.fromString(requestId));
		InputStream input = taskFilesDirectory.child().file(fileName, useExisting()).inputStream();
		IOUtil.exchange(input, response.getOutputStream());
	}
}
